package com.catazy.jetpackstudy.act2.chapter2.serial

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.PermissionUtils
import com.catazy.jetpackstudy.databinding.ActivityMainBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.ObjectInputStream
import java.io.ObjectOutputStream


/**
 * - 作者: Tao
 * - 日期: 2025/1/15
 * - 时间: 09:42
 * - 描述:
 */
class MainActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "MainActivity"
    }

    private val mBinding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(mBinding.root)

        initPermission()

        // 第二章
        mBinding.serial.setOnClickListener {
            logI("序列化点击")
            lifecycleScope.launch(Dispatchers.IO) {
                val user = User(1, "Tao", true)
                logI("序列化得到的 user: $user")
                val out = ObjectOutputStream(openFileOutput("user.txt", MODE_PRIVATE))
                out.writeObject(user)
                out.close()
            }
        }

        mBinding.deserial.setOnClickListener {
            logI("反序列化点击")
            lifecycleScope.launch(Dispatchers.IO) {
                val inStream = openFileInput("user.txt")
                val user = ObjectInputStream(inStream).readObject() as User
                inStream.close()
                logI("反序列化得到的 user: $user")
            }
        }
    }

    private fun initPermission(){
        PermissionUtils.permissionGroup(PermissionConstants.STORAGE)
            .callback(object : PermissionUtils.FullCallback {
                override fun onGranted(granted: MutableList<String>) {
                    logI("接受权限")
                }

                override fun onDenied(
                    deniedForever: MutableList<String>,
                    denied: MutableList<String>
                ) {
                    logI("拒绝权限")
                }

            })
            .request()
    }

    private fun logI(msg:String){
        Log.i(TAG, Thread.currentThread().name + "----> " +msg)
    }
}